package com.study.securitydemo.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author weiyongpeng
 * @ClassName: MyAuthenticationEntryPoint
 * @Description: 请求未认证处理器
 * @date 2024/10/26
 */
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        // 获取异常信息
        String localizedMessage = "请先登录";

        // 创建对象
        Map result = new HashMap();
        result.put("code",1);
        result.put("message",localizedMessage);

        // 创建json结果,将结果转化为json字串
        String json = JSON.toJSONString(result);
        // 将json字串返回前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}